package base

import (
	"devOpsApi/libs"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/kataras/iris"
	"github.com/kataras/iris/sessions"
)

type BController struct {
	Ctx     iris.Context
	Session *sessions.Session
}

/**
输出json
*/
func (B *BController) OutDataJson(outData interface{}, code int, msg string, debug ...string) {
	putData := make(map[string]interface{})
	putData["code"] = code
	putData["message"] = msg
	putData["data"] = outData

	if len(debug) > 0 {
		putData["debug"] = debug[0]
	}

	B.Ctx.JSON(putData)
}

func (B *BController) OutDataXml(outData string, code int, msg string) {
	type Result struct {
		Code int    `xml:"code"`
		Msg  string `xml:"msg"`
		Data string `xml:"data"`
	}
	B.Ctx.XML(Result{
		Code: code,
		Msg:  msg,
		Data: outData,
	})
}

/**
输出json 使用缓存
cacheTime 缓存时间 0为默认的30S
*/
func (B *BController) OutDataJsonCache(outData interface{}, code int, msg string, cacheTime int64) {
	putData := make(map[string]interface{})
	putData["code"] = code
	putData["message"] = msg
	putData["data"] = outData
	libs.SetCache(B.Ctx, putData, time.Duration(cacheTime*1e9)) //设置缓存
	B.Ctx.JSON(putData)
}

/**
允许跨域
*/
func (B *BController) crossDomain() {
	B.Ctx.Header("Access-Control-Allow-Origin", "*")
}

func (B *BController) Dump(data interface{}) {
	fmt.Println("============================")
	fmt.Printf("%+v \n", data)
	fmt.Println("============================")
}


func (b *BController) Oauth2Url(giturl string, gitlabToken string) (oauthUrl string, err error) {
	splitArray := strings.Split(giturl, "://")
	if len(splitArray) == 2 {
		oauthUrl = splitArray[0] + "://oauth2:" + gitlabToken + "@" + splitArray[1]
		return
	}
	return "", errors.New("Git仓库地址错误！")
}
